package org.budo.ocr.service.baidu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.budo.ocr.service.api.OcrRequest;
import org.budo.ocr.service.api.OcrResponse;
import org.budo.ocr.service.impl.ByteArrayOcrRequest;
import org.budo.ocr.service.impl.DefaultOcrResponse;
import org.budo.ocr.service.impl.FileOcrRequest;
import org.budo.ocr.service.impl.UrlOcrRequest;
import org.budo.support.lang.util.FileUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;

import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
public class BaiduAiOcrService extends AbstractBaiduAiOcrService {
    @Override
    public OcrResponse recognition(OcrRequest request) {
        if (null == request) {
            log.error("#27 recognition, request=" + request);
            return null;
        }

        AipOcr client = this.getAipOcr();

        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject responseJson = null;

        if (request instanceof ByteArrayOcrRequest) {
            byte[] byteArray = ((ByteArrayOcrRequest) request).getByteArray();
            responseJson = client.basicGeneral(byteArray, options);
        } else if (request instanceof FileOcrRequest) {
            String filePath = FileUtil.getCanonicalPath(((FileOcrRequest) request).getFile());
            responseJson = client.basicGeneral(filePath, options);
        } else if (request instanceof UrlOcrRequest) {
            String url = ((UrlOcrRequest) request).getUrl();
            responseJson = client.basicGeneralUrl(url, options);
        } else {
            throw new IllegalArgumentException("#40 request.type=" + request.getClass());
        }

        if (null == responseJson.opt("words_result")) {
            log.error("#30 no words_result, responseJson=" + responseJson);
            return null;
        }

        JSONArray wordsResult = responseJson.getJSONArray("words_result");
        if (null == wordsResult || wordsResult.length() < 1) {
            log.error("#28 wordsResult=" + wordsResult + ", responseJson=" + responseJson);
            return null;
        }

        List<String> words = new ArrayList<String>();
        for (Object each : wordsResult) {
            JSONObject json = (JSONObject) each;
            words.add(json.getString("words"));
        }

        DefaultOcrResponse response = new DefaultOcrResponse(words);
        log.info("#41 request=" + request + ", response=" + response);
        return response;
    }
}